﻿using AutoMapper;
using Newtonsoft.Json;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Zocono.Infrastructure.Common;
using Zocono.WCS.Domain.DomainRepository;
using Zocono.WCS.Domain.EntityInfo;
using Zocono.WCS.Domain.LogDomain;
using Zocono.WCS.Domain.PlcBytesObject;
using Zocono.WCS.Domain.PlcConnectionDomain;
using Zocono.WCS.Domain.PlcConnectPoolDomain;
using Zocono.WCS.Domain.ProcessModuleDomain;
using Zocono.WCS.Infrastructure.ApllicationDto.DtoWcsManage;
using Zocono.WCS.Infrastructure.ApllicationDto.Enums;
using Zocono.WCS.Infrastructure.ApllicationDto.WCSTaskDto;
using Zocono.WCS.Infrastructure.PlcCommon;
using Zocono.WCS.WMSApiDomain.WebApi;

namespace Zocono.WCS.Domain.EquipmentProcessDomain.PlanarGeneralMessage
{
    /// <summary>
    /// 电池信息校验服务
    /// </summary>
    public class BatteryCheckInfoService : IPlanarGeneralPlcActionProcessService
    {
        private readonly IRedisHelper _IRedisHelper;
        private readonly ISnowflake _snowflake;
        private readonly ILogUtil _logUtil;
        private readonly IMapper _mapper;
        private readonly IPlcConnectionPool _plcConnectionPool;
        private readonly IWorkTaskInfoRepository _workTaskInfoRepository;
        private readonly IPlcWriteDbInfoRepository _plcWriteDbInfoRepository;
        private readonly IPlcConnectionInfoRepository _PlcConnectionInfoRepository;
        private readonly IPlcPointInfoRepositpry _IPlcPointInfoRepositpry;
        private readonly IPlcConnectionStateInfoRepository _IPlcConnectionStateInfoRepository;
        private readonly IRunLogInfoService _IRunLogInfoService;
        private readonly IPlcReadDbInfoRepository _PlcReadeDbInfoRepository;

        public BatteryCheckInfoService(IRedisHelper iRedisHelper, ISnowflake snowflake, ILogUtil logUtil, IMapper mapper,
            IPlcConnectionPool plcConnectionPool, IWorkTaskInfoRepository workTaskInfoRepository
            , IPlcWriteDbInfoRepository plcWriteDbInfoRepository
            , IPlcPointInfoRepositpry plcPointInfoRepositpry
             , IPlcConnectionInfoRepository plcConnectionInfoRepository
           , IPlcConnectionStateInfoRepository plcConnectionStateInfoRepository
            , IRunLogInfoService runLogInfoService, IPlcReadDbInfoRepository plcReadDbInfoRepository)
        {
            _IRedisHelper = iRedisHelper;
            _snowflake = snowflake;
            _logUtil = logUtil;
            _mapper = mapper;
            _plcConnectionPool = plcConnectionPool;
            _workTaskInfoRepository = workTaskInfoRepository;
            _plcWriteDbInfoRepository = plcWriteDbInfoRepository;
            _PlcConnectionInfoRepository = plcConnectionInfoRepository;
            _IPlcPointInfoRepositpry = plcPointInfoRepositpry;
            _IPlcConnectionStateInfoRepository = plcConnectionStateInfoRepository;
            _IRunLogInfoService = runLogInfoService;
            _PlcReadeDbInfoRepository = plcReadDbInfoRepository;
        }

        public async Task ProcessActionMessageAsync(BytesObjectBase plcActionMessage, BytesObjectBase wcsActionMessage, EquipmentDbObject planarEquipmentDbObject/*, BytesObjectBase plcStateMassge*/)
        {
            /*
             *  需求说明
                1.判断plc状态与设备状态（仅报警处理）
                2.根据任务状态【待执行、执行中】查询wcs托盘上架任务是否存在?（存在则直接回复正常报文 否则请求wms下发入库上架任务）
                  NA说明：1) 根据wms下发任务生成wcs任务
                          2）计算wcs任务路径id【RouteInfo】第一条路径明细【RouteDetailInfo】作为wcs子任务【WorkTaskInfo】Cuttent部分
                          3）更新wms任务状态为执行中
                3.逻辑处理完成 则开始写入Plc 写入成功则处理WCS操作数据库业务 否则不操作
                  说明：1）默认wcs ActionType 跟随Plc ActionType值 即Plc ActionType为 1 则wcs ActionType回写也为 1 
                        2）针对Plc离线或设备状态报警程序直接return
                         plc动作报文托盘号为空或wms请求巷道任务失败 则响应握手类型 =100表示报警
             */


            var plcMessage = plcActionMessage as PlanarGeneralPlcActionBO;//Plc的动作报文
            var wcsMessage = wcsActionMessage as PlanarGeneralWcsActionBO;//Wcs的动作报文
            plcMessage.PalletBarcode = plcMessage.PalletBarcode.Trim();

            RunLogInfo runLogInfo = new();
            runLogInfo.ContainerBarcode = plcMessage.PalletBarcode;
            runLogInfo.EquipmentCode = plcMessage.EquipmentCode;
            runLogInfo.RunType = "电池信息校验";

            //var plcStateBo = plcStateMassge as PlcOnLineStateBO;//Plc在线离线报文 没有设备信息
            PlanarGeneralWriteWcsAction writeBo = null;//写入Plc的报文
            PlcConnectionS7 plcConn = _plcConnectionPool.S7GetWritePlcConnection(plcMessage.PlcConnectionID);//plc写入连接（不锁定）


            #region Plc离线判断


            if (plcConn == null)
            {
                //runLogInfo.RunLog = $"获取连接({writeBo.PlcConnectionID})失败";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】电池信息校验，PLC设备【{plcMessage.PlcConnectionID}】不存在连接池中！");
                return;
            }

            //runLogInfo.RunLog = "任务开始：电池信息校验任务开始";
            //1. 验证plc是否在线
            var plcIPStates = await _IPlcConnectionStateInfoRepository.GetFirstAsync(l => l.PlcConnectionID == plcMessage.PlcConnectionID && l.Connected == true);
            if (plcIPStates == null)
            {
                //runLogInfo.RunLog = $"离线：请求分配失败：{plcConn.IP}:plc已离线";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】电池信息校验，PLC设备【{plcMessage.EquipmentCode}】离线！");
                return;
            }


            #endregion

            #region plc写入连接获取&写入报文构建
            //Plc连接Id
            long plcId = wcsMessage.PlcConnectionID;
            //写入plc的报文配置获取
            var objectType = typeof(PlanarGeneralWriteWcsAction).Name;
            var writeConfig = await _plcWriteDbInfoRepository.GetFirstAsync(s => s.EquipmentCode == plcMessage.EquipmentCode && s.ObjectType == objectType);
            if (writeConfig == null)
            {

                //runLogInfo.RunLog = "获取PLC写入配置失败";
                //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】电池信息校验，PLC设备【{plcMessage.EquipmentCode}】写DB配置获取失败！请检查配置！");
                return;
            }

            //构建写入报文
            writeBo = new PlanarGeneralWriteWcsAction(
                writeConfig.PlcConnectionId,
                writeConfig.ID,
                writeConfig.DbCode,
                writeConfig.DbStart,
                objectType,
                plcMessage.EquipmentCode.ToInt32(),
                //Convert.ToInt32(writeConfig.EquipmentCode),
                plcMessage.ActionType,
                0,
                0,
                palletBarcode: plcMessage.PalletBarcode,
                plcMessage.PalletType,
                0);
            ////线体报警
            //if (plcMessage.AlrmCode > 0)
            //{
            //    writeBo.ActionType = 99;
            //    writeBo.AlrmCode = 101;
            //    var res = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
            //    _logUtil.Error($"电池信息校验：电池信息校验，PLC设备【{plcMessage.EquipmentCode}】PLC报警！");
            //    _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
            //    return;
            //}

            //托盘号不存在 
            if (string.IsNullOrEmpty(plcMessage.PalletBarcode) || plcMessage.PalletBarcode.Length != 10)
            {
                writeBo.ActionType = 99;
                writeBo.AlrmCode = 102;
                var res = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                _logUtil.Error($"电池信息校验：电池信息校验，PLC设备【{plcMessage.EquipmentCode}】读取托盘信息为空！请检查PLC信息是否写入信息");
                _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
                return;
            }


            //托盘类型
            switch (writeBo.PalletBarcode.Substring(1, 1))
            {
                case "A":
                    writeBo.PalletType = 2;
                    break;
                case "B":
                    writeBo.PalletType = 1;
                    break;
                case "C":
                    writeBo.PalletType = 3;
                    break;
            }
            #endregion



            #region 托盘号不存在&wcs托盘上架任务已存在逻辑处理

            //获取条码的电芯数据
            if (plcMessage.ActionType == 34) {

                //请求WMS获取电芯信息
                try
                {
                    var bo = await WCSMessageWithWMSApi.GetContainerBatteryAsync(plcMessage.PalletBarcode, plcMessage.EquipmentCode);
                    if (bo.IsSucceed && bo.Result.CellDataDtos.Any())
                    {
                        //判断1通道是否有电芯
                        var oneBattery = bo.Result.CellDataDtos.Any(x => x.CellPosttion == "1");
                        //1通道有电芯回plc 1 没有回plc 2
                        writeBo.ActionType = (short)(oneBattery ? 1 : 2);

                        var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                        if (res)
                        {
                            runLogInfo.RunLog = $"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息成功，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        }
                        else
                        {
                            _logUtil.Error($"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息成功，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                        }
                        return;

                    }
                    else
                    {
                        writeBo.ActionType = 36;
                        writeBo.AlrmCode = 2;
                        var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                        if (res)
                        {
                            runLogInfo.RunLog = $"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息失败，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                            _logUtil.Error(runLogInfo.RunLog);
                        }
                        else
                        {
                            _logUtil.Error($"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息失败，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                        }
                        return;
                    }
                }
                catch (Exception ex)
                {
                    writeBo.ActionType = 99;
                    var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                    if (res)
                    {
                        runLogInfo.RunLog = $"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息报错：{ex.Message}，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                        _logUtil.Error(runLogInfo.RunLog);
                    }
                    else
                    {
                        _logUtil.Error($"获取电芯信息：托盘【{plcMessage.PalletBarcode}】获取电芯信息报错：{ex.Message}，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                    }
                    return;
                }

            }

            //校验条码
            if (plcMessage.ActionType == 35)
            {
                //获取电芯条码得DB块信息，进行读取
                var plcConfigput = await _PlcReadeDbInfoRepository.GetFirstAsync(l => l.EquipmentCode == plcMessage.EquipmentCode + "-BAT");

                //读取电芯和位置PLC报文
                byte[] bytes = await plcConn.ReadDbAsync(plcConfigput.DbCode, plcConfigput.DbStart, plcConfigput.DbLength);
                if (bytes == null)
                {
                    //runLogInfo.RunLog = $"读DB失败";
                    //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    writeBo.ActionType = 99;
                    writeBo.AlrmCode = 0;
                    var res = await plcConn.WriteDbAsync(writeBo.DbCode, writeBo.DbStart, writeBo.Deserialize());
                    _IRedisHelper.SetStringKey($"PLC-{plcMessage.EquipmentCode}", plcMessage.EquipmentCode.ToString() + plcMessage.AlrmCode, TimeSpan.FromSeconds(10));
                    _logUtil.Error($"电池信息校验：电池信息校验，PLC设备【{plcMessage.EquipmentCode}-BAT】读取DB获取电芯条码失败！");
                    return;
                }

                //解析电芯和位置报文信息
                PlanarBatteryPlcActionBO plcActionBO = new();
                plcActionBO.Serialize(plcConfigput.PlcConnectionID, plcConfigput.ID, plcConfigput.DbStart, plcConfigput.DbLength, plcConfigput.DbStart, plcConfigput.DbLength, "PlanarBatteryPlcActionBO", plcConfigput.EquipmentCode, bytes);//主要是bytes转化成明文
                                                                                                                                                  
                //解析后电芯数据为0
                if (plcActionBO.BatteryItems.Count == 0)
                {
                    //runLogInfo.RunLog = $"电池条码为空或位置信息为0";
                    //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                    writeBo.ActionType = 36;
                    var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                    if (res)
                    {
                        runLogInfo.RunLog = $"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口校验电芯失败，解析出电芯信息数为0，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        _logUtil.Error(runLogInfo.RunLog);
                    }
                    else
                    {
                        //runLogInfo.RunLog = $"电池条码为空或位置信息为写入报文失败";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口校验电芯失败，解析出电芯信息数为0，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                    }
                    return;
                }

                //请求WMS校验接口报文类
                WCSCombinePalletInfoDto wCSCombinePalletInfoDto = new()
                {
                    ContainerBarcode = plcMessage.PalletBarcode,
                    EquipmentCode = plcMessage.EquipmentCode
                };

                List<WCSOneBatteryDto> list = new();
                //组合电芯信息
                foreach (BatteryItemDto batteryItem in plcActionBO.BatteryItems)
                {
                    WCSOneBatteryDto batteryItemTemp = new()
                    {
                        BatteryIndex = batteryItem.BatteryIndex,
                        BatteryCode = batteryItem.BatteryCode
                    };
                    list.Add(batteryItemTemp);
                }


                wCSCombinePalletInfoDto.oneBatteryInfoDtos = list;

                //3 4楼实盘投入口不申请任务直接返回
                //string[] inEqs = { "320601", "320603", "320605", "420521", "420523", "420525", "330473", "410503", "410506" };
                //组盘提交数据到WMS
                try
                {
                    var bo = await WCSMessageWithWMSApi.WCSAddComPalletAsync(wCSCombinePalletInfoDto);
                    if (bo)
                    {
                        //runLogInfo.RunLog = $"投料校验成功";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        //if (inEqs.Contains(plcMessage.EquipmentCode.Trim()))
                        //{
                        writeBo.ActionType = plcMessage.ActionType;
                        var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                        if (res)
                        {
                            runLogInfo.RunLog = $"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口校验电芯成功，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                            await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        }
                        else
                        {
                            //runLogInfo.RunLog = $"托盘校验写入报文失败:托盘校验成功，未申请任务。";
                            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口校验电芯成功，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                        }
                        return;
                        //}
                    }
                    else
                    {
                        writeBo.ActionType = 36;
                        writeBo.AlrmCode = 2;
                        var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                        if (res)
                        {
                            runLogInfo.RunLog = $"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口WMS校验电芯失败，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            _logUtil.Error(runLogInfo.RunLog);
                        }
                        else
                        {
                            //runLogInfo.RunLog = $"投料校验写入报文失败:投料校验失败";
                            //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                            _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口WMS校验电芯失败，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                        }
                        return;
                    }
                }
                catch (Exception ex)
                {
                    writeBo.ActionType = 36;
                    var res = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, writeBo.Deserialize());
                    if (res)
                    {
                        runLogInfo.RunLog = $"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口WMS校验电芯报错：{ex.Message}，PLC设备【{plcMessage.EquipmentCode}】写入PLC成功！写入报文：{JsonConvert.SerializeObject(writeBo)}";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        _logUtil.Error(runLogInfo.RunLog);
                    }
                    else
                    {
                        //runLogInfo.RunLog = $"投料校验写入报文失败:投料校验WMS请求失败";
                        //await _IRunLogInfoService.AddRunLogInfoAsync(runLogInfo);
                        _logUtil.Error($"电池信息校验：托盘【{plcMessage.PalletBarcode}】投料口WMS校验电芯报错：{ex.Message}，PLC设备【{plcMessage.EquipmentCode}】写入PLC失败！");
                    }
                    return;
                }

            }


            #endregion


        }

        /// <summary>
        /// 根据写入db配置将报文写入plc
        /// </summary>
        /// <param name="equipmentCode">设备编号</param>
        /// <param name="plcConnectionId"></param>
        /// <param name="bytes"></param>
        /// <returns></returns>
        private async Task<bool> WriteDbAsync(string equipmentCode, long plcConnectionId, byte[] bytes)
        {
            var plcConn = _plcConnectionPool.S7GetWritePlcConnection(plcConnectionId);
            //根据设备编号获取写入配置
            var writeConfig = await _plcWriteDbInfoRepository.GetSingleAsync(s => s.EquipmentCode == equipmentCode
            && s.PlcConnectionId == plcConnectionId && s.ObjectType == typeof(PlanarGeneralWriteWcsAction).Name);
            //写入报文处理
            bool isSend = await plcConn.WriteDbAsync(writeConfig.DbCode, writeConfig.DbStart, bytes);
            if (isSend)
                _logUtil.Info($"设备号{equipmentCode}plc连接ID{plcConnectionId} 写入报文成功");
            else
                _logUtil.Info($"设备号{equipmentCode}plc连接ID{plcConnectionId} 写入报文失败");
            return isSend;
        }

    }
}
